package com.xju.controller;

import com.xju.entity.CartItem;
import com.xju.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/CartServlet")
public class CartServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        if (user == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        CartDao cartDao = new CartDao();

        if ("add".equals(action)) {
            int productId = Integer.parseInt(request.getParameter("productId"));
            int quantity = 1; // 默认数量为1
            cartDao.addToCart(user.getId(), productId, quantity);
            response.sendRedirect("CartServlet"); // 重定向到 CartServlet 以获取最新的购物车数据
        } else if ("remove".equals(action)) {
            int productId = Integer.parseInt(request.getParameter("productId"));
            cartDao.removeFromCart(user.getId(), productId);
            response.sendRedirect("CartServlet"); // 重定向到 CartServlet 以获取最新的购物车数据
        } else if ("checkout".equals(action)) {
            cartDao.clearCart(user.getId());
            session.setAttribute("checkoutMessage", "结算成功！");
            response.sendRedirect("CartServlet"); // 重定向到 CartServlet 以获取最新的购物车数据
        } else {
            List<CartItem> cartItems = cartDao.getCartItems(user.getId());
            double totalPrice = 0;
            for (CartItem cartItem : cartItems) {
                totalPrice += cartItem.getProduct().getPrice() * cartItem.getQuantity();
            }
            request.setAttribute("cartItems", cartItems);
            request.setAttribute("totalPrice", totalPrice);
            request.getRequestDispatcher("cart.jsp").forward(request, response);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
